package mlta.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


public class SearchActivity extends Activity {
	protected EditText editSearch;
	protected Button bSearch;
	protected Button btn_help, btn_exit, btn_all, btn_back;
	protected int textlength=0;
	protected ListView listView;
	protected int id;
	protected long course_id = -1;
	protected long topic_id = -1;
	protected String username;
	protected boolean novo = false;

	protected String titulo;

	protected String message;
    
	
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	        setContentView(R.layout.search);
	        id = getIntent().getIntExtra("tipo", 1);
	        course_id = getIntent().getLongExtra("course_id", -1);
	        topic_id = getIntent().getLongExtra("topic_id", -1);
	        username = getIntent().getStringExtra("username");
	        novo = getIntent().getBooleanExtra("novo", false);
			titulo = getIntent().getStringExtra("titulo");
			message = getIntent().getStringExtra("message");
	        
	        btn_help = (Button) findViewById(R.id.search_help);
	        btn_exit = (Button) findViewById(R.id.search_exit);
	        btn_all = (Button) findViewById(R.id.search_all);
	        btn_back = (Button) findViewById(R.id.search_back);
	             
	        btn_help.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Toast.makeText(getApplicationContext(), "Feature not ready yet!!!", Toast.LENGTH_LONG).show();
				}
				
			});
	        
	        btn_exit.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					System.exit(0);
				}
				
			});
	        
	     // evento botao old
			btn_all.setOnClickListener(new View.OnClickListener() {

				public void onClick(View arg0) {
					Intent intent = new Intent(SearchActivity.this, SearchActivity.class);
					intent.putExtra("tipo", id);
					intent.putExtra("course_id", course_id);
					intent.putExtra("topic_id", topic_id);
					intent.putExtra("username", username);
					intent.putExtra("novo", novo);
					intent.putExtra("titulo", titulo);
					intent.putExtra("message", message);
					SearchActivity.this.startActivity(intent);
				}

			});

			// evento botao voltar
			btn_back.setOnClickListener(new View.OnClickListener() {

				public void onClick(View arg0) {
					if(id == 1) {
						Intent intent = new Intent(SearchActivity.this, CoursesActivity.class);
						intent.putExtra("username", username);
						SearchActivity.this.startActivity(intent);
						System.exit(0);
					} else if(id == 2) {
						Intent intent = new Intent(SearchActivity.this, CoursesTopicActivity.class);
						intent.putExtra("id", course_id);
						intent.putExtra("username", username);
						intent.putExtra("novo", novo);
						intent.putExtra("titulo", titulo);
						intent.putExtra("message", message);
						SearchActivity.this.startActivity(intent);
						System.exit(0);
					} else if(id == 3) {
						Intent intent = new Intent(SearchActivity.this, CommentsActivity.class);
						intent.putExtra("topic_id", topic_id);
						intent.putExtra("course_id", course_id);
						intent.putExtra("username", username);
						intent.putExtra("novo", novo);
						intent.putExtra("titulo", titulo);
						intent.putExtra("message", message);
						SearchActivity.this.startActivity(intent);
						System.exit(0);
					}
				}

			});

	        

	        listView = (ListView) findViewById(R.id.topics);

			final ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

			SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.course,
	              new String[] {"course", "unread"}, new int[] {R.id.label, R.id.count}); 
			HashMap<String, String> map;
			if(id == 1) {
				map = new HashMap<String, String>();
		        map.put("course", "Fundamentos de Interação Usuário-Computador");
		        map.put("unread", "(8)");
		        list.add(map);

		        map = new HashMap<String, String>();
		        map.put("course", "Fundamentos de Sistemas Hipermídia e Web");
		        map.put("unread", "(0)");
		        list.add(map);
		        
		        map = new HashMap<String, String>();
		        map.put("course", "Fundamentos de Multimídia");
		        map.put("unread", "(0)");
		        list.add(map);
		        
		        map = new HashMap<String, String>();
		        map.put("course", "Engenharia de Software");
		        map.put("unread", "(0)");
		        list.add(map);
		        
		        map = new HashMap<String, String>();
		        map.put("course", "Teste de Software");
		        map.put("unread", "(0)");
		        list.add(map);
			            
			        adapter = new SimpleAdapter(this, list, R.layout.course,
			                new String[] {"course", "unread"}, new int[] {R.id.label, R.id.count}); 
			}
			else if (id == 2){
				map = new HashMap<String, String>();
				map.put("Topic", "Data da Prova");
				map.put("unread", "(5)");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("Topic", "Parte 1 do Projeto");
				map.put("unread", "(1)");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("Topic", "Horario: Aula 15/05");
				map.put("unread", "(1)");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("Topic", "Dúvidas sobre a Parte 1 do Projeto");
				map.put("unread", "(1)");
				list.add(map);
					
					adapter = new SimpleAdapter(this, list, R.layout.topic,
							new String[] { "Topic", "unread" }, new int[] { R.id.label,R.id.count });
			}
			else if(id == 3) {
				map = new HashMap<String, String>();
				map.put("count", "3");
				map.put("name", "MARIA JOSÉ DA SILVA");
				map.put("date", "7d");
				map.put("message", "Alguém sabe o dia da prova?");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("count", "10");
				map.put("name", "ANTONIO MANUEL");
				map.put("date", "3d");
				map.put("message", "Acho que é dia 30/06?");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("count", "5");
				map.put("name", "CARLOS RODRIGUES");
				map.put("date", "1h");
				map.put("message", "O que é que vai cair?");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("count", "1");
				map.put("name", "BIANCA MELO");
				map.put("date", "30m");
				map.put("message", "Acho que até a aula 6.");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("count", "0");
				map.put("name", "JULIANA RIBEIRO");
				map.put("date", "20s");
				map.put("message", "A aula 7 não cai?");
				list.add(map);

				map = new HashMap<String, String>();
				map.put("count", "0");
				map.put("name", "BIANCA MELO");
				map.put("date", "7d");
				map.put("message", ":(");
				list.add(map);

					
					adapter = new SimpleAdapter(this, list, R.layout.comment,
							new String[] { "count", "name", "date", "message" }, new int[] {
									R.id.comment_count, R.id.comment_name,
									R.id.comment_date, R.id.comment_message });

			}
					
			listView.setAdapter(adapter);
			
			        
	        editSearch = (EditText) findViewById(R.id.editSearch);
	        bSearch = (Button) findViewById(R.id.bSearch);
	        
	        
	        editSearch.addTextChangedListener(new TextWatcher() {
	        	public void afterTextChanged1(Editable s) {
	        		// Abstract Method of TextWatcher Interface.
	        	}
	        	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	        		// Abstract Method of TextWatcher Interface.
	        	}
	        	public void onTextChanged(CharSequence s, int start, int before, int count) {
	        	/*	System.out
							.println("SearchActivity.onCreate(...).new TextWatcher() {...}.onTextChanged()");
	        		textlength = editSearch.getText().length();
	        		ArrayList<HashMap<String, String>> newList = new ArrayList<HashMap<String, String>>();
	        		newList.clear();
	        		for (int i = 0; i < list.size(); i++) {
	        			Set<String> chaves = list.get(i).keySet();  
		        	    for (String chave : chaves)  {   
		        	    	//System.out.println(list.get(i).get(chave).toString());
		        	    	try {
									if( editSearch.toString()
											.equalsIgnoreCase((String) list.get(i).get(chave).toString()
													.subSequence(0,textlength-1) ))
									      newList.add(list.get(i));
								} catch (StringIndexOutOfBoundsException e) {
									System.err.println("Erro no limite da string\n\n" + e.toString());  
								}
	        			}
	                }
	        		SimpleAdapter adp1 = new SimpleAdapter(SearchActivity.this, list, R.layout.course,
	    	                new String[] {"course", "unread"}, new int[] {R.id.label, R.id.count}); 
	        		if(id == 1) {
	        			 adp1 = new SimpleAdapter(SearchActivity.this, newList, R.layout.course,
	 			                new String[] {"course", "unread"}, new int[] {R.id.label, R.id.count}); 
	        		} else if(id == 2) {
	        			adp1 = new SimpleAdapter(SearchActivity.this, list, R.layout.topic,
								new String[] { "Topic", "unread" }, new int[] { R.id.label,R.id.count });
	        		} else if (id == 3) {
	        			adp1 = new SimpleAdapter(SearchActivity.this, newList, R.layout.comment,
								new String[] { "count", "name", "date", "message" }, new int[] {
								R.id.comment_count, R.id.comment_name,
								R.id.comment_date, R.id.comment_message });
	        		}
	        		
	        		listView.setAdapter(adp1); */
	        	}
				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}
	        });
	        
	        bSearch.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) { 
					//Função de pesquisa
					//Log.v("blah", "blah blah");
					textlength = editSearch.getText().length();
					ArrayList<HashMap<String, String>> newList = new ArrayList<HashMap<String, String>>();
	        		newList.clear();
	        		//System.out.println(list.size());
	        		for (int i = 0; i < list.size(); i++) {
	        			Set<String> chaves = list.get(i).keySet();  
		        	    for (String chave : chaves)  {   
		        	    	//System.out.println(list.get(i).get(chave).toString());
		        	    	try {
									if( editSearch.getText().toString()
											.equalsIgnoreCase((String) list.get(i).get(chave).toString()
													.subSequence(0,textlength) )) {
									      newList.add(list.get(i));
										System.out.println("Inseriu!"); }
								} catch (StringIndexOutOfBoundsException e) {
									System.err.println("Erro no limite da string\n\n" + e.toString());  
								}
	        			}
	                }
	        		SimpleAdapter adp1 = new SimpleAdapter(SearchActivity.this, newList, R.layout.course,
	    	                new String[] {"course", "unread"}, new int[] {R.id.label, R.id.count}); 
	        		if(id == 1) {
	        			 adp1 = new SimpleAdapter(SearchActivity.this, newList, R.layout.course,
	 			                new String[] {"course", "unread"}, new int[] {R.id.label, R.id.count}); 
	        		} else if(id == 2) {
	        			adp1 = new SimpleAdapter(SearchActivity.this, newList, R.layout.topic,
								new String[] { "Topic", "unread" }, new int[] { R.id.label,R.id.count });
	        		} else if (id == 3) {
	        			adp1 = new SimpleAdapter(SearchActivity.this, newList, R.layout.comment,
								new String[] { "count", "name", "date", "message" }, new int[] {
								R.id.comment_count, R.id.comment_name,
								R.id.comment_date, R.id.comment_message });
	        		}
	        		//System.out.println(list.size());
	        		
	        		listView.setAdapter(adp1);
	        		
	        		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(editSearch.getWindowToken(), 0);
	        		
	        	}
				
			});
					
					        
	 }
	 

	 
	 @Override
	    public void onBackPressed() {
		 if(id == 1) {
				Intent intent = new Intent(SearchActivity.this, CoursesActivity.class);
				intent.putExtra("username", username);
				SearchActivity.this.startActivity(intent);
				System.exit(0);
			} else if(id == 2) {
				Intent intent = new Intent(SearchActivity.this, CoursesTopicActivity.class);
				intent.putExtra("id", course_id);
				intent.putExtra("username", username);
				intent.putExtra("novo", novo);
				intent.putExtra("titulo", titulo);
				intent.putExtra("message", message);
				SearchActivity.this.startActivity(intent);
				System.exit(0);
			} else if(id == 3) {
				Intent intent = new Intent(SearchActivity.this, CommentsActivity.class);
				intent.putExtra("topic_id", topic_id);
				intent.putExtra("course_id", course_id);
				intent.putExtra("username", username);
				intent.putExtra("novo", novo);
				intent.putExtra("titulo", titulo);
				intent.putExtra("message", message);
				SearchActivity.this.startActivity(intent);
				System.exit(0);
			}
	    }
	 
}
